package com.zuikaku.service.impl;

import com.github.pagehelper.PageHelper;
import com.zuikaku.dao.OrderMapper;
import com.zuikaku.pojo.Item;
import com.zuikaku.pojo.Order;
import com.zuikaku.pojo.User;
import com.zuikaku.service.ItemService;
import com.zuikaku.service.OrderService;
import com.zuikaku.vo.OrderVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private ItemService itemService;

    @Override
    public List<OrderVO> queryOrderVOByPage(int pageCount, int pageSize) {
        return orderMapper.queryOrderVOByPage((pageCount-1)*pageSize,pageSize);
    }

    @Override
    public List<Order> getOrdersByItemIdAndUserId(Integer userId, Integer itemId) {
        Map<String,Integer> parameter = new HashMap<>();
        parameter.put("itemId",itemId);
        parameter.put("userId",userId);
        return orderMapper.getOrderByItemAndUser(parameter);
    }

    @Override
    public List<Order> getOrdersByIds(List<Integer> collect) {
        return orderMapper.getOrderByUsers(collect);
    }

    @Override
    public OrderVO getOrderVOByPk(Integer id) {
        return orderMapper.getOrderVOByPk(id);
    }

    @Override
    public int addOrderByOrder(Order order) {
        return orderMapper.insertSelective(order);
    }

    @Transactional(rollbackFor = Throwable.class)
    @Override
    public String createOrder(User activeUser, Integer itemId) {
        Item item = itemService.getItemByPk(itemId);
        if(item !=null){
            item.setCount(item.getCount()-1);
            int res1 = itemService.updateItemByItem(item);
            Order order =new Order();
            order.setCount(1);
            order.setFkUserId(activeUser.getUserId());
            order.setFkItemId(itemId);
            order.setOrderPrice((int)(long)item.getUnitPrice());
            order.setOrderName("API下单："+item.getItemName());
            order.setCreateDate(new Date());
            order.setOrderStatus(1);
            int a =1/0;
            int res2 = addOrderByOrder(order);
            if(res1>0&&res2>0){
                return "ok";
            }else {
                return "fail";
            }

        }else {

            return "no exist item";
        }
    }
}
